package com.longcai.controller.nearby;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.longcai.bean.ApiResult;
import com.longcai.bean.PageHelper;
import com.longcai.entity.homepage.GoodsClass;
import com.longcai.entity.nearby.ClyjNearbyShops;
import com.longcai.mapper.nearby.ClyjNearbyShopsMapper;
import com.longcai.page.table.PageTableResponse;
import com.longcai.service.goods.GoodsClassService;
import com.longcai.service.nearby.ClyjNearbyShopsService;
import com.longcai.util.OSSUtils;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 附近商铺 前端控制器
 * </p>
 *
 * @author ZZN
 * @since 2019-04-11
 */
@RestController
@RequestMapping("/clyjNearbyShops")
public class ClyjNearbyShopsController {

    private Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private ClyjNearbyShopsService clyjNearbyShopsService;
    @Autowired
    private ClyjNearbyShopsMapper clyjNearbyShopsMapper;
    @Autowired
    GoodsClassService bannerService;

    /**
     * 获取店铺信息
     *
     * @param clyjNearbyShops
     * @return
     */
    @ApiOperation(value = "店铺列表")
    @GetMapping(value = "/clyshopsList")
    public PageTableResponse shopsList(ClyjNearbyShops clyjNearbyShops, PageHelper pageHelper) {
        return this.clyjNearbyShopsService.shopsList(clyjNearbyShops, pageHelper);
    }

    /**
     * 所有菜单
     *
     * @return
     */
    @GetMapping("/all")
    @ApiOperation(value = "所有菜单")
    @ResponseBody
    public JSONArray goodsClassAll() {
        QueryWrapper<GoodsClass> queryWrapper = new QueryWrapper<GoodsClass>();
        queryWrapper.eq("type", "2");
        List<GoodsClass> selectList = bannerService.selectList(queryWrapper);
        queryWrapper.orderByAsc("type_sort");
        JSONArray array = new JSONArray();
        setPermissionsTree("0", selectList, array);
        return array;
    }

    /**
     * 菜单树
     *
     * @param pId
     * @param permissionsAll
     * @param array
     */
    private void setPermissionsTree(String pId, List<GoodsClass> permissionsAll, JSONArray array) {
        permissionsAll.forEach(a -> {
            if ((pId.equals("0") && a.getPId() == null) || (a.getPId() != null && a.getPId().equals(pId))) {
                String string = JSONObject.toJSONString(a);
                JSONObject parent = (JSONObject) JSONObject.parse(string);
                array.add(parent);

                if (permissionsAll.stream().filter(p -> p.getPId() != null && p.getPId().equals(a.getId())).findAny() != null) {
                    JSONArray child = new JSONArray();
                    parent.put("child", child);
                    setPermissionsTree(a.getId(), permissionsAll, child);
                }
            }
        });
    }

    /**
     * 删除店铺
     *
     * @param id
     */
    @DeleteMapping("/{id}")
    @ApiOperation(value = "删除店铺")
    @PreAuthorize("hasAuthority('shops:delete')")
    public void deleteShopsList(@PathVariable String id) {
        this.clyjNearbyShopsService.deleteShopsList(id);
    }

    /**
     * 审核店铺
     *
     * @param id
     */
    @GetMapping("/up/{id}")
    @ApiOperation(value = "审核店铺")
    @PreAuthorize("hasAuthority('shops:flag')")
    public ApiResult updateshops(@PathVariable String id) {
        try {
            QueryWrapper<ClyjNearbyShops> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("shops_id", id);
            ClyjNearbyShops clyjNearbyShops = this.clyjNearbyShopsMapper.selectOne(queryWrapper);
            clyjNearbyShops.setFlag(1);
            this.clyjNearbyShopsMapper.updateById(clyjNearbyShops);
            logger.info("修改成功");
            return ApiResult.success("修改成功");
        } catch (Exception e) {
            logger.error("修改失败");
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 修改店铺
     *
     * @param clyjNearbyShops
     * @param logo1
     * @param picture1
     * @param topP
     * @param corporateCardPic1
     * @param corporateBankCardPic1
     * @param pictureIn1
     * @return
     */
    @PostMapping(value = "/updateShopsList")
    @PreAuthorize("hasAuthority('shops:update')")
    public ApiResult updateShopsList(ClyjNearbyShops clyjNearbyShops, MultipartFile logo1, MultipartFile picture1, MultipartFile topP, MultipartFile corporateCardPic1, MultipartFile corporateBankCardPic1, MultipartFile pictureIn1) {
        if (logo1 != null) {
            //文档上传oss
            try {
                String fileName = logo1.getOriginalFilename();
                String pox = fileName.substring(fileName.lastIndexOf(".") + 1);
                InputStream inputStream = logo1.getInputStream();
                Map<String, Object> uploadByInputStream = OSSUtils.uploadByInputStream(inputStream, pox, "CLYJ/NEARBYSHOPS/");
                clyjNearbyShops.setLogo(uploadByInputStream.get("path").toString());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (picture1 != null) {
            //文档上传oss
            try {
                String fileName = picture1.getOriginalFilename();
                String pox = fileName.substring(fileName.lastIndexOf(".") + 1);
                InputStream inputStream = picture1.getInputStream();
                Map<String, Object> uploadByInputStream = OSSUtils.uploadByInputStream(inputStream, pox, "CLYJ/NEARBYSHOPS/");
                clyjNearbyShops.setPictureOut(uploadByInputStream.get("path").toString());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (topP != null) {
            //文档上传oss
            try {
                String fileName = topP.getOriginalFilename();
                String pox = fileName.substring(fileName.lastIndexOf(".") + 1);
                InputStream inputStream = topP.getInputStream();
                Map<String, Object> uploadByInputStream = OSSUtils.uploadByInputStream(inputStream, pox, "CLYJ/NEARBYSHOPS/");
                clyjNearbyShops.setTopPicture(uploadByInputStream.get("path").toString());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (corporateCardPic1 != null) {
            //文档上传oss
            try {
                String fileName = corporateCardPic1.getOriginalFilename();
                String pox = fileName.substring(fileName.lastIndexOf(".") + 1);
                InputStream inputStream = corporateCardPic1.getInputStream();
                Map<String, Object> uploadByInputStream = OSSUtils.uploadByInputStream(inputStream, pox, "CLYJ/NEARBYSHOPS/");
                clyjNearbyShops.setCorporateCardPic(uploadByInputStream.get("path").toString());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (corporateBankCardPic1 != null) {
            //文档上传oss
            try {
                String fileName = corporateBankCardPic1.getOriginalFilename();
                String pox = fileName.substring(fileName.lastIndexOf(".") + 1);
                InputStream inputStream = corporateBankCardPic1.getInputStream();
                Map<String, Object> uploadByInputStream = OSSUtils.uploadByInputStream(inputStream, pox, "CLYJ/NEARBYSHOPS/");
                clyjNearbyShops.setCorporateBankCardPic(uploadByInputStream.get("path").toString());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (pictureIn1 != null) {
            //文档上传oss
            try {
                String fileName = pictureIn1.getOriginalFilename();
                String pox = fileName.substring(fileName.lastIndexOf(".") + 1);
                InputStream inputStream = pictureIn1.getInputStream();
                Map<String, Object> uploadByInputStream = OSSUtils.uploadByInputStream(inputStream, pox, "CLYJ/NEARBYSHOPS/");
                clyjNearbyShops.setPictureIn(uploadByInputStream.get("path").toString());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        List<String> typeIds = clyjNearbyShops.getTypeIds();
        if (typeIds == null || typeIds.size() == 0) {
            return ApiResult.fail("修改失败");
        } else {
            String s = typeIds.get(typeIds.size() - 1);
            clyjNearbyShops.setShopsType(s);
            this.clyjNearbyShopsService.updateById(clyjNearbyShops);
            return ApiResult.success("修改成功");
        }
    }

    /**
     * 根据id获取信息
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "根据id获取店铺信息")
    @GetMapping("/{id}")
    @PreAuthorize("hasAuthority('shops:query')")
    public ApiResult getById(@PathVariable String id) {
        return this.clyjNearbyShopsService.getById(id);
    }

    /**
     * 店铺上线
     *
     * @param id
     * @return
     */
    @GetMapping("/ups/{id}")
    @PreAuthorize("hasAuthority('shops:up')")
    public ApiResult upShop(@PathVariable String id) {
        return this.clyjNearbyShopsService.upShop(id);
    }
    /**
     * 店铺下线
     *
     * @param id
     * @return
     */
    @GetMapping("/down/{id}")
    @PreAuthorize("hasAuthority('shops:down')")
    public ApiResult downShop(@PathVariable String id) {
        return this.clyjNearbyShopsService.downShop(id);
    }

    /**
     * 审核通过更改店铺信息
     *
     * @param clyjNearbyShops
     * @return
     */
    @PostMapping("/saveShops")
    @PreAuthorize("hasAuthority('shops:update')")
    public ApiResult saveShops(ClyjNearbyShops clyjNearbyShops) {
        return this.clyjNearbyShopsService.saveShops(clyjNearbyShops);
    }

    /**
     * 获取所有店铺名称
     *
     * @return
     */
    @RequestMapping("/getshops")
    public List<ClyjNearbyShops> getshops() {

        return clyjNearbyShopsService.getAllshops();
    }


}

